﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace ComponentsLib
{
    public partial class Movable : UserControl
    {
        private bool isMoving = false;
        private Size preCursor;
        private Point preLocation;

        public delegate bool AcceptMoving(Point currPos);

        public event AcceptMoving OnAcceptMoving;
        
        public Movable()
        {
            InitializeComponent();
        }

        private void Movable_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == System.Windows.Forms.MouseButtons.Left)
            {
                isMoving = true;
                preCursor = new Size(e.Location);
                preLocation = this.Location;   
            }            
        }

        private void Movable_MouseUp(object sender, MouseEventArgs e)
        {
            isMoving = false;
            bool accept = true;
            if (OnAcceptMoving != null)
            {
                accept = OnAcceptMoving.Invoke(this.Location);   
            }

            if (accept)
            {

            }
            else
            {
                this.Location = preLocation;
            }
        }

        private void Movable_MouseMove(object sender, MouseEventArgs e)
        {
            if (isMoving)
            {
                //((Movable)((Control)sender).GetContainerControl()).Location +=
                //    new Size(e.Location - preCursor);
                this.Location += new Size(e.Location - preCursor);
            }
        }

        private void SetMovableEvent(Control control)
        {
            foreach (Control item in control.Controls)
            {
                item.MouseDown += Movable_MouseDown;
                item.MouseUp += Movable_MouseUp;
                item.MouseMove += Movable_MouseMove;
                SetMovableEvent(item);
            }
        }

        private void Movable_Load(object sender, EventArgs e)
        {
            SetMovableEvent(sender as Control);
        }

        private void Movable_ControlAdded(object sender, ControlEventArgs e)
        {
            SetMovableEvent(e.Control);
        }


    }
}
